<template>
  <!-- 开放申报入口 -->
  <div class="app-container">
    <!-- 按钮 -->
    <div class="clearfix">
      <el-button
        type="primary"
        icon="el-icon-s-promotion"
        @click="onclickRuzhiApply"
      >
        开放申报入口
      </el-button>
      <el-button
        type="danger"
        :disabled="!ids.length"
        @click="(e) => delInfo()"
      >
        批量删除
      </el-button>
      <el-form class="fr" inline>
        <el-form-item>
          <el-date-picker
            v-model="queryParams2.year"
            type="year"
            placeholder="选择年份"
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      element-loading-text="Loading"
      :data="list"
      :header-cell-style="{ background: '#ECF1F9' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50px" align="center" />
      <el-table-column label="序号" type="index" width="80px" align="center" />

      <el-table-column label="名称" align="center">
        <template slot-scope="scope">
          {{ scope.row.reportName ? scope.row.reportName : "--" }}
        </template>
      </el-table-column>

      <el-table-column label="发布时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.updateTime ? scope.row.updateTime : "--" }}
        </template>
      </el-table-column>

      <el-table-column label="年度" align="center">
        <template slot-scope="scope">
          {{ scope.row.year ? scope.row.year : "--" }}
        </template>
      </el-table-column>

      <el-table-column label="开始时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.startTime ? scope.row.startTime : "--" }}
        </template>
      </el-table-column>

      <el-table-column label="截止时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.endTime ? scope.row.endTime : "--" }}
        </template>
      </el-table-column>

      <el-table-column label="申报状态" align="center">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.status == 'NOT_START'"
            >未开始</el-tag
          >
          <el-tag v-if="scope.row.status == 'CANCEL'" type="warning"
            >已撤销</el-tag
          >

          <el-tag type="success" v-if="scope.row.status == 'FINISHED'"
            >已结束</el-tag
          >
          <el-tag type="success" v-if="scope.row.status == 'PROCEED'"
            >进行中</el-tag
          >
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center">
        <template slot-scope="scope">
          {{ scope.row.note ? scope.row.note : "--" }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250px" align="center">
        <template slot-scope="scope">
          <el-link @click="updateInfo(scope.row)" type="primary">编辑</el-link>

          <el-link
            @click="cancelInfo(scope.row.id)"
            type="warning"
            style="margin: 0 10px"
            >撤销</el-link
          >

          <el-link @click="delInfo(scope.row.id)" type="danger">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 对话框 -->
    <el-dialog
      :title="dialogTitle"
      width="40%"
      :visible.sync="ruzhiApplyDialog.visible"
      top="5vh"
      center
      :show-close="false"
    >
      <el-form
        :model="dialogForm"
        ref="formRef"
        label-width="120px"
        :rules="formRules"
      >
        <el-form-item label="名称" prop="reportName">
          <el-input
            v-model="dialogForm.reportName"
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="申报年份" prop="year">
          <el-date-picker
            style="width: 100%"
            v-model="dialogForm.year"
            type="year"
            placeholder="选择申报年份"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            style="width: 100%"
            v-model="dialogForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            style="width: 100%"
            v-model="dialogForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="dialogForm.note"
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="reset">取 消</el-button>
        <el-button type="primary" @click="submitData('formRef')"
          >提 交</el-button
        >
      </div>
    </el-dialog>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams2.pageNum"
      :limit.sync="queryParams2.pageSize"
      @pagination="getTreeData"
    />
  </div>
</template>

<script>
import moment from "moment";
import { websock } from "@/websock";
import { Message } from "element-ui";
import { quchongAuditors } from "@/utils/utils";

import {
  apiOpenDeclaration, //列表
  apiSaveReport, //创建
  apidelReport, //删除
  apicancelReport, //撤销
  apiupdateReport, //更新
} from "@/api2/projectManagement/reporting";

export default {
  components: {},
  watch: {
    "queryParams2.year"(val) {
      if (val) {
        this.queryParams2.year = this.getFormatedYear(val);
      } else {
        this.queryParams2.year = null;
      }
      this.getTreeData();
    },
  },
  data() {
    // 校验开始时间
    var startTimeRuls = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请选择开始时间"));
      }
      let startTime = this.dialogForm.startTime.getFullYear();
      let year = this.dialogForm.year;

      if (!year) {
        return callback(new Error("请先选择申报年份"));
      } else {
        if (year != startTime) {
          return callback(new Error("开始时间范围选择错误"));
        } else {
          callback();
        }
      }
    };
    // 检验结束时间
    var endTimeRuls = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请选择结束时间"));
      }
      let endTime = new Date(this.dialogForm.endTime).getFullYear();
      let year = this.dialogForm.year;
      // console.log(endTime, year);

      if (!year) {
        return callback(new Error("请先选择申报年份"));
      } else {
        if (year != endTime) {
          return callback(new Error("结束时间范围选择错误"));
        } else {
          callback();
        }
      }
    };

    return {
      ids: [], //批量删除选中的id数组
      total: 0,
      queryParams2: {
        pageNum: 1,
        pageSize: 10,
        year: null,
      },
      year: 0,
      dialogTitle: "开放申报入口",
      // --------
      dialogForm: {
        year: "",
        startTime: "",
        endTime: "",
      },
      departmentList: null,
      positionList: null,
      userList: [],
      userList1: [],
      list: [],
      pageIndex: 1,
      pageCount: 10,
      dataTotal: 0,
      listLoading: false,
      auditors: [],
      ruzhiApplyDialog: {
        visible: false,
        name: "",
        gonghao: "",
        department: "",
        position: "",
        leixing: "无类型",
        upper: [],
        xingzhi: "在编人员",
        gender: "未知",
        trialTime: "",
        ruzhiDate: "",
        phone: "",
        email: "",
        remark: "",
        auditors: [],
      },
      detailDialog: {
        visible: false,
        id: 0,
      },
      // 数据校验
      formRules: {
        reportName: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        year: [{ required: true, message: "请选择申报年份", trigger: "blur" }],
        // startTime: [{ validator: startTimeRuls, trigger: "blur" }],
        // endTime: [{ validator: endTimeRuls, trigger: "blur" }],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "change" },
        ],
        endTime: [
          { required: true, message: "请选择结束时间", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getTreeData();
  },
  methods: {
    // 获取格式化时间字符串 年
    getFormatedYear(stamp, str = "YYYY") {
      return moment(stamp).format(str);
    },
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = "YYYY-MM-DD HH:mm") {
      // console.log(stamp);
      return moment(stamp).format(str);
    },

    // 批量删除选择
    handleSelectionChange(val) {
      this.ids = val.map((item) => item.id);
    },

    // 更新
    updateInfo(row) {
      this.dialogTitle = "修改开放申报信息";
      this.ruzhiApplyDialog.visible = true;
      this.dialogForm = row;
      this.dialogForm.year = row.year + "";
    },

    // 撤销
    cancelInfo(id) {
      this.$confirm("确认撤销该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            id,
          };
          apicancelReport(data)
            .then((res) => {
              if (res.code == 0) {
                this.$message({
                  type: "success",
                  message: "撤销成功!",
                });
              } else {
                this.$message({
                  type: "error",
                  message: "撤销失败!",
                });
              }
              this.getTreeData();
            })
            .catch((err) => {
              this.$message({
                type: "error",
                message: "撤销失败!",
              });
              this.getTreeData();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消撤销",
          });
        });
    },

    // 删除
    delInfo(id) {
      this.$confirm("确定删除" + (id ? "此项" : "已选中的") + "数据吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const ids = id ? id : this.ids.join();
          apidelReport(ids)
            .then((res) => {
              if (res.code == 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
              } else {
                this.$message({
                  type: "error",
                  message: "删除失败!",
                });
              }
              this.getTreeData();
            })
            .catch((err) => {
              this.$message({
                type: "error",
                message: "删除失败!",
              });
              this.getTreeData();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 获取数据列表
    getList() {
      this.listLoading = true;
      this.getTreeData();
      this.listLoading = false;
    },

    getTreeData() {
      apiOpenDeclaration(this.queryParams2).then((res) => {
        this.total = res.total;
        this.list = res.data;
      });
    },

    gonghaoChange() {
      this.ruzhiApplyDialog.gonghao =
        parseInt(this.ruzhiApplyDialog.gonghao) + "";
    },
    departChange(e) {
      this.getAuditors();
    },
    // 获取审核人
    async getAuditors() {
      try {
        this.ruzhiApplyDialog.auditors = [];
        let defaultAuditors = this.auditors.slice();
        for (let i = 0; i != defaultAuditors.length; i++) {
          if (defaultAuditors[i].sta == "1") {
            if (this.ruzhiApplyDialog.department === "") continue;
            let departId =
              this.departmentList[this.ruzhiApplyDialog.department].id;
            let lingdao = await websock.getDepartmentLingdao({ departId });
            if (lingdao.zhijie_lingdao) {
              this.ruzhiApplyDialog.auditors.push({
                uid: lingdao.zhijie_lingdao,
                name: lingdao.zhijie_lingdao_name,
                positionName: lingdao.zhijie_lingdao_position_name,
              });
            }
          } else if (defaultAuditors[i].sta == "0") {
            this.ruzhiApplyDialog.auditors.push(defaultAuditors[i]);
          }
        }
        quchongAuditors(this.ruzhiApplyDialog.auditors);

        // console.log("get auditors", this.ruzhiApplyDialog.auditors);
      } catch (err) {
        console.error(err);
        this.$message.error({ title: err.message || "error" });
      }
    },
    reset() {
      this.getTreeData();
      this.ruzhiApplyDialog.visible = false;
      this.dialogForm = {};
      this.$nextTick(() => {
        this.$refs["formRef"].clearValidate();
      });
    },
    onclickRuzhiApply() {
      this.ruzhiApplyDialog.visible = true;
      this.getAuditors();
    },
    submitData(name) {
      let year = this.getFormatedYear(this.dialogForm.year);
      let startTime = this.getFormatedTimeStr(
        this.dialogForm.startTime
      ).substring(0, 4);
      let endTime = this.getFormatedTimeStr(this.dialogForm.endTime).substring(
        0,
        4
      );
      if (year != startTime) {
        this.msgInfo("申报年份与开始时间不一致");
        return;
      }
      if (year != endTime) {
        this.msgInfo("申报年份与结束时间不一致");
        return;
      }

      let data;
      this.$refs[name].validate((valid) => {
        // console.log(valid);
        if (valid) {
          data = {
            year: this.getFormatedYear(this.dialogForm.year),
            startTime: this.getFormatedTimeStr(this.dialogForm.startTime),
            endTime: this.getFormatedTimeStr(this.dialogForm.endTime),
            reportName: this.dialogForm.reportName,
            note: this.dialogForm.note,
          };
          // console.log(data);

          // 修改
          if (this.dialogForm.id) {
            data.id = this.dialogForm.id;
            data.status = this.dialogForm.status;
            apiupdateReport(data)
              .then((res) => {
                // console.log(res);
                if (res.code == 0) {
                  this.msgSuccess("更新成功");
                } else {
                  this.msgError("更新失败");
                }
                this.ruzhiApplyDialog.visible = false;
                this.dialogForm = {};
                this.getTreeData();
              })
              .catch((err) => {
                console.log(err);
                this.msgError("更新失败");
              });
            // 提交
          } else {
            apiSaveReport(data)
              .then((res) => {
                // console.log(res);
                if (res.code == 0) {
                  this.msgSuccess("操作成功");
                } else {
                  this.msgError("操作失败");
                }
                this.ruzhiApplyDialog.visible = false;
                this.dialogForm = {};
                this.getTreeData();
              })
              .catch((err) => {
                console.log(err);
                this.msgError("操作失败");
              });
          }
        }
      });
    },

    seeDetail(id) {
      this.detailDialog.visible = true;
      this.detailDialog.id = id;
    },
    printPdf(id) {
      websock.printPdf({ typ: 3, id }).then((res) => {
        // console.log("print pdf", res);
        const a = document.createElement("a");
        a.style.display = "none";
        a.href = res;
        a.target = "_blank";
        document.body.appendChild(a);
        a.click();
        URL.revokeObjectURL(a.href);
        document.body.removeChild(a);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
// @import url("../../../styles/form.css");
.app-container {
  height: 100%;
  background: #f4f5fc;
}
::v-deep .el-dialog__header {
  text-align: left;
}
::v-deep .el-upload {
  width: 100%;
}
</style>
